package com.wbcs.system.datatype;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Element;

public abstract class AbsNumberType extends AbsDataType
{
    private final static Log log=LogFactory.getLog(AbsNumberType.class);

    protected String numberformat;

    @Override
	public void loadTypeConfig(Element eleDataType)
    {
        if(eleDataType==null) return;
        numberformat=eleDataType.attributeValue("defaultformat");
        numberformat=numberformat==null?"":numberformat.trim();
        if(numberformat.equals("")) numberformat=null;
    }

    @Override
	public IDataType setUserConfigString(String configstring)
    {
        if(configstring==null||configstring.trim().equals("")) return this;
        configstring=configstring.trim();
        if(getAllMNumberTypeObjects().containsKey(configstring))
        {
            return getAllMNumberTypeObjects().get(configstring);
        }
        AbsNumberType newNumberType=null;
        try
        {
            newNumberType=(AbsNumberType)super.clone();
            newNumberType.numberformat=configstring;
            getAllMNumberTypeObjects().put(configstring,newNumberType);
        }catch(CloneNotSupportedException e)
        {
            e.printStackTrace();
        }
        return newNumberType;
    }

    protected Number getNumber(String strvalue)
    {
        if(strvalue==null||strvalue.trim().equals("")) strvalue="0";
        if(this.numberformat!=null&&!this.numberformat.trim().equals(""))
        {
            DecimalFormat df=new DecimalFormat(this.numberformat);
            Number n=0;
            try
            {
                n=df.parse(strvalue.trim());
            }catch(ParseException e)
            {
                log.error(strvalue+"不是合法的"+this.numberformat+"格式的字节",e);
                n=0;
            }
            return n;
        }else
        {
            return null;
        }
    }
    
    protected abstract Map<String,AbsNumberType> getAllMNumberTypeObjects();
}
